<template>
    <div>
        <div style="border:1px solid black;height:150px;">
        <el-container>
        <el-header>
            <span class="left">筛选查询</span>
        </el-header>
        <el-main>
            <el-form :inline="true" :model="searchMap" class="demo-form-inline">
            <el-form-item label="输入搜索：">
                <el-input v-model="searchMap.title" placeholder="相册名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
             </el-form>
        </el-main>
        </el-container>
       </div>
        <div style="border:1px solid black;height:750px;margin-top:25px;">
        <el-container>
        <el-header>
            <span class="left">数据列表</span>
            <div style="float:right;">
            <el-button class="header_right" id="xj"  @click="dialogFormVisible=true; brandForm={}; imageUrl=''">新建相册</el-button>
            </div>
        </el-header>
        <el-main>
        <el-table :data="tableData" style="width: 100%" @selection-change="selectChange">
        <el-table-column
        type="selection"
        width="55">
        </el-table-column>
        <el-table-column prop="id" label="编号" width="100"></el-table-column>
        <el-table-column prop="title" label="相册名称" width="100"></el-table-column>
        <el-table-column width="200" label="封面">
          <template slot-scope="scope">
               <img style="height:100px;" :src="scope.row.image" class="avatar" />
          </template>
        </el-table-column>
        <el-table-column width="100"  label="图片数量">
        <template slot-scope="scope">
            <span>{{numList[scope.$index]}}</span>
        </template>
        </el-table-column>
        <el-table-column width="150" prop="describes" label="描述"></el-table-column>
        <el-table-column width="250" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="$router.push({path:'/detailed',query:{ 'title' :scope.row.title}})">查看</el-button>
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
        </el-table-column>
        </el-table>
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="pageSizeList"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            ></el-pagination>
        </el-main>
        </el-container>
       </div>

       <el-dialog :title="brandForm.id==null?'新增':'编辑'" :visible.sync="dialogFormVisible">
      <el-form :model="brandForm">
        <el-form-item label="相册名称" :label-width="formLabelWidth">
          <el-input v-model="brandForm.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="相册封面" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="'http://localhost:88/api/oss/upload/oss?folder=myimages&classify=' + this.brandForm.title"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" style="height:100px;"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="相册描述" :label-width="formLabelWidth">
          <el-input v-model="brandForm.describes" autocomplete="off">this.brandForm.title</el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false; brandForm={}">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
        formLabelWidth: '150px',
        dialogFormVisible: false,
        tableData: [],
        total: 0,
        currentPage: 1,
        pageSize: 5,
        pageSizeList: [5, 10, 20, 30],
        searchMap: {},
        numList: [],
        brandForm: {},
        imageUrl: ""
        }
    },
    methods: {
        toggleSelection(rows) {
            if (rows) {
            rows.forEach(row => {
                this.$refs.multipleTable.toggleRowSelection(row);
            });
            } else {
            this.$refs.multipleTable.clearSelection();
            }
        },
        selectChange(val) {
            this.multipleSelection = val;
        },
        async getList () {
          var date1 = new Date()
          console.log(this.searchMap)
            const { data: res } = await this.$http.post(
            `goods/album/findPage?pageNo=${this.currentPage}&pageSize=${this.pageSize}`,
            this.searchMap
        );
        var date2 = new Date()
        if (this.dateMinus(date1, date2) > 0) {
          this.$message('网页加载较慢，感谢您的耐心等待!');
        }
        this.tableData = res.data.rows;
        this.total = res.data.total;
      for (let i = 0; i < this.tableData.length; i++) {
        var num = 0;
        if (this.tableData[i].imageItems != null) {
        var ii = this.tableData[i].imageItems;
        num = JSON.parse(ii).length
        // if (this.tableData[i].image != null) {
        //     num += 1
        // }
      }
        this.numList.push(num)
      }
        },
    onSubmit () {
      this.currentPage = 1;
      this.getList();
    },
    async handleEdit (index, row) {
      this.dialogFormVisible = true;
      const id = row.id;
      const { data: res } = await this.$http.get(`goods/album/findById/${id}`);
      this.brandForm = res.data;
      this.imageUrl = this.brandForm.image
    },
    async handleDelete (index, row) {
      const id = row.id;
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          // const str = row.image.split("/")
          // console.log(str[2])
          // if (str[2] === 'w-xian.oss-cn-hangzhou.aliyuncs.com') {
          //   console.log(row.image)
          //   this.$http.post(`http://localhost:84/api/oss/upload/ossDelete?fileName=${row.image}`)
          // }
          const { data: res } = await this.$http.post(`goods/album/delete?id=${id}`);
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.getList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async handleSizeChange (val) {
      this.pageSize = val;
      this.getList();
    },
    async handleCurrentChange (val) {
      this.currentPage = val;
      this.getList();
    },
    async save () {
      this.brandForm.image = this.imageUrl
      this.dialogFormVisible = false;
      const { data: res } = await this.$http.post(
        `goods/album/${this.brandForm.id == null ? "insert" : "update"}`,
        this.brandForm
      );
      if (res.code === 200) {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.getList();
      }
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = file.response;
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    dateMinus(data1, date2) {
            var s1 = data1.getTime()
            var s2 = date2.getTime()
            var total = (s2 - s1) / 1000
            var day = parseInt(total / (24 * 60 * 60))
            var afterDay = total - day * 24 * 60 * 60
            var hour = parseInt(afterDay / (60 * 60))
            var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60
            var min = parseInt(afterHour / 60)
            var afterMin = total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60
            return afterMin
        }
    },
    created() {
        this.getList()
    }
}
</script>

<style scoped>
.el-header {
  background-color: rgba(228, 228, 228, 1);
  color: #333;
  text-align: center;
  line-height: 60px;
}
.left {
  float: left;
}
.header_right {
  margin-left: 15px;
}
</style>
